<template>
   <div class=''>
       <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item><a href="/">商品管理</a></el-breadcrumb-item>
            <el-breadcrumb-item>参数列表</el-breadcrumb-item>
        </el-breadcrumb>

        <el-card>
            <el-alert show-icon title="注意：只允许第三级分类设置相关参数！" type="warning" :closable="false"></el-alert>
            <!-- 商品分类区域 -->
            <el-row class="cat_opt">
                <el-col>
                    <span>选择商品分类：</span>
                    <!-- 选择商品分类联级选择框 -->
                     <el-cascader
                        v-model="selectedKeys"
                        :options="cateList"
                        :props="cascaderProps"
                        @change="cateChange"
                        clearable
                    ></el-cascader>
                </el-col>
            </el-row>

              <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="动态参数" name="many">
                    <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addData">动态参数</el-button>
                    <!-- 动态参数表格 -->
                    <el-table :data="manyTableData" border stripe>
                        <!-- 展开行 -->
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <!-- 循环渲染tag标签 -->
                                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="item.atte_id" closable
                                @close="handleClose(i,scope.row)">
                                    {{ item}}
                                </el-tag>

                                <el-input
                                    class="input-new-tag"
                                    v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue"
                                    ref="saveTagInput"
                                    size="small"
                                    @keyup.enter.native="handleInputConfirm(scope.row)"
                                    @blur="handleInputConfirm(scope.row)"
                                    >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <!-- 索引列 -->
                        <el-table-column type="index"></el-table-column>
                        <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" size="mini" icon="el-icon-edit"  @click="editData(scope.row.attr_id)">编辑</el-button>
                                <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeDataById(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>

                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="静态属性" name="only">
                    <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addData">静态属性</el-button>
                    <!-- 静态属性表格 -->
                    <el-table :data="onlyTableData" border stripe>
                        <!-- 展开行 -->
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <!-- 循环渲染tag标签 -->
                                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="item.atte_id" closable
                                @close="handleClose(i,scope.row)">
                                    {{ item}}
                                </el-tag>

                                <el-input
                                    class="input-new-tag"
                                    v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue"
                                    ref="saveTagInput"
                                    size="small"
                                    @keyup.enter.native="handleInputConfirm(scope.row)"
                                    @blur="handleInputConfirm(scope.row)"
                                    >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <!-- 索引列 -->
                        <el-table-column type="index"></el-table-column>
                        <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" size="mini" icon="el-icon-edit" @click="editData(scope.row.attr_id)">编辑</el-button>
                                <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeDataById(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>

                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>


         <!-- 添加参数弹窗 -->
        <el-dialog
            :title="titleText"
            :visible.sync="addDataDialogVisible"
            @close="addDataDialogClose"
            width="50%">
            <el-form :model="addDataForm" ref="addDataFormRef" label-width="95px" :rules="addCateFormRules">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="addDataForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDataDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addDataSumbit">确 定</el-button>
            </span>
        </el-dialog> 

        <!-- 修改参数弹窗 -->
        <el-dialog
            :title="titleText"
            :visible.sync="editDataDialogVisible"
            @close="editDataDialogClose"
            width="50%">
            <el-form :model="editDataForm" ref="editDataFormRef" label-width="95px" :rules="addCateFormRules">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="editDataForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDataDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editDataSumbit">确 定</el-button>
            </span>
        </el-dialog> 
   </div>
</template>

<script>
export default {
    data(){
        return {
            cateList:[],
            cascaderProps:{
                value:'cat_id',
                label:'cat_name',
                children:'children',
            },
            selectedKeys:[],
            activeName:'many',
            manyTableData:[],   //动态参数数据
            onlyTableData:[],   //静态属性数据
            addDataDialogVisible:false,
            addDataForm:{
                attr_name:'',
            },
            addCateFormRules:{
                attr_name:[
                    { required: true, message: '请输入分类名称', trigger: 'blur' },
                ],
            },
            editDataDialogVisible:false,
            editDataForm:{
                attr_name:'',
            },
        }
    },
    created(){
        //获取商品分类
        this.getCateList()
    },
    methods:{
        // 获取商品分类列表
        async getCateList(){
            const {data:res} = await this.$http.get('categories')
            if(res.meta.status !==200) return this.$message.error("获取商品分类失败")
            this.cateList = res.data
            console.log(this.cateList)
        },
        cateChange(){
            this.getParamsDate();
        },
        // 标签页切换
        handleClick(){
            this.getParamsDate();
        },
        //获取参数列表数据
        async getParamsDate(){
            if(this.selectedKeys.length!==3) {
                this.selectedKeys = []
                this.onlyTableData = []
                this.manyTableData = []
                return
            }
            //根据所选的分类和当前面板，获取相应的参数、
            
            const {data:res} =await this.$http.get(`categories/${this.cateId}/attributes`,{params:{sel:this.activeName}})
            if(res.meta.status !==200) return this.$message.error("获取参数列表失败")
            // 将后台返回的长串字符串通过空格切割成一个数组
            res.data.forEach(item=>{
                item.attr_vals = item.attr_vals ? item.attr_vals.split(',') :[]
                item.inputVisible = false
                item.inputValue = ''
            })
            // console.log(res.data)
            if(this.activeName=='many'){
                this.manyTableData = res.data
            }else{
                this.onlyTableData = res.data
            }
        },
        addDataSumbit(){
            this.$refs.addDataFormRef.validate(async valid=>{
                if(!valid) return
                const {data:res} = await this.$http.post(`categories/${this.cateId}/attributes`,{
                    attr_name:this.addDataForm.attr_name,
                    attr_sel:this.activeName
                })
                if(res.meta.status !== 201) return this.$message.error("添加参数失败")
                this.$message.success("添加参数成功")
                this.addDataDialogVisible = false
                this.getParamsDate()
            })
        },
        //打开添加弹窗
        addData(){
            this.addDataDialogVisible = true
        },
        //关闭添加弹窗
        addDataDialogClose(){
            this.$refs.addDataFormRef.resetFields()
        },
         //打开修改弹窗
        async editData(attr_id){
            const {data:res} = await this.$http.get(`categories/${this.cateId}/attributes/${attr_id}`,
            {
                params:{ attr_sel:this.activeName }
            })
            if(res.meta.status !== 200) return this.$message.error("获取参数失败")
            this.editDataForm = res.data

            this.editDataDialogVisible = true
        },
        //关闭修改弹窗
        editDataDialogClose(){
            this.$refs.editDataFormRef.resetFields()
        },
        editDataSumbit(){
            this.$refs.editDataFormRef.validate(async valid=>{
                if(!valid) return
                const {data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${this.editDataForm.attr_id}`,{
                    attr_name:this.editDataForm.attr_name,
                    attr_sel:this.activeName
                })
                if(res.meta.status !== 200) return this.$message.error("修改参数失败")
                this.$message.success("修改参数成功")
               
                this.getParamsDate()
                this.editDataDialogVisible = false
            })
        },
        // 删除参数
        async removeDataById(attr_id){
            const confirmResulr = await this.$confirm(
                '此操作将永久删除参数信息，是否继续',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }
            ).catch(err=>err)
            if(confirmResulr!=='confirm') return this.$message.info("已取消删除")
            const {data:res} = await this.$http.delete(`categories/${this.cateId}/attributes/${attr_id}`)
            if(res.meta.status !== 200) return this.$message.error("用户删除失败")
            this.$message.success("参数删除成功")
            console.log(confirmResulr)
            //刷新表格
            this.getParamsDate();
        },
        // 文本框失去焦点
        async handleInputConfirm(row){
            // 判断输入是否为空
            if(row.inputValue.trim().length==0){
                row.inputValue = ""
                row.inputVisible = false
                return 
            }
            // 否则则有值，将输入的值加到tab标签数组中
            row.attr_vals.push(row.inputValue.trim())
            row.inputValue = ""
            row.inputVisible = false
            // 向后端发送请求
           this.saveAttrVals(row)
        },
        // 点击按钮展示文本
        showInput(row){
            row.inputVisible=true
            // 当页面被重新渲染之后，才会回调函数、
            this.$nextTick(()=>{
                this.$refs.saveTagInput.$refs.input.focus()
            })
        },
        // 删除标签操作
        handleClose(i,row){
            row.attr_vals.splice(i,1);
            this.saveAttrVals(row)
        },
        async saveAttrVals(row){
            const {data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
                attr_name:row.attr_name,
                attr_sel:row.attr_sel,
                attr_vals:row.attr_vals.join(",")
            })
            if(res.meta.status !== 200) return this.$message.error("修改参数失败")
            this.$message.success("修改参数成功")
        }
    },
    // 计算属性
    computed:{
        //如果没有选中分类，按钮不可点击
        isBtnDisabled(){
            if(!(this.selectedKeys.length>0)){
                return true
            }
            return false
        },
        // 获取选中的三级分类ID
        cateId(){
            if(this.selectedKeys.length===3){
                return this.selectedKeys[2]
            }
            return null
        },
        // 动态计算标题文本
        titleText(){
            if(this.activeName=='many'){
                return '动态参数'
            }
            return '静态属性'
        }
    }
}
</script>
<style lang="less" scoped>
.cat_opt{
    margin-top: 15px;
}
.el-tag{
    margin-right: 10px;
}
.input-new-tag{
    width: 120px;
}
</style>